package com.example.learnnacos;

import com.example.learnnacos.clients.svc.HelloClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.CallableWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.*;

@Slf4j
@RestController
@RefreshScope
public class HelloController {

    @Value("${config.say}")
    private String say;

    @Autowired
    private HelloClient helloClient;

    private ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 120, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

    @GetMapping("/hello/say")
    public Map<String, Object> index() throws ExecutionException, InterruptedException {
        log.info("one call");

        // 使用CallableWrapper进行异步链路封装
        Future<Map<String, Object>> future = executor.submit(new CallableWrapper<>(() -> {
            Map<String, Object> map = helloClient.callHello();
            log.info("executor submit result: {}", map);
            return map;
        }));

        Map<String, Object> map = future.get();
        map.put("say", say);
        return map;
    }

    @GetMapping("/hello/syncsay")
    public Map<String, Object> syncSay() {
        Map<String, Object> map = helloClient.callHello();
        map.put("say", say);
        return map;
    }

}
